// 2013-8-1下午06:04:07  net.betou.trade.main.dao.impl.TradeDaoImpl.java

package net.betou.trade.main.dao.impl;

import java.util.List;

import net.betou.common.hibernate3.Finder;
import net.betou.common.hibernate3.HibernateBaseDao;
import net.betou.common.page.Pagination;
import net.betou.trade.entity.main.Trade;
import net.betou.trade.main.dao.TradeDao;

import org.hibernate.Criteria;
import org.springframework.stereotype.Repository;

/**
 * 
 * @author 叶装装
 */
@Repository
public class TradeDaoImpl extends HibernateBaseDao< Trade, Integer > implements TradeDao{

	public Trade deleteById( Integer id ) {
		Trade bean = get( id );
		if( bean != null ){
			getSession( ).delete( bean );
		}
		return bean;
	}

	public Trade findById( Integer id ) {
		return get( id );
	}

	public Trade findMyTrade( Integer userid, Integer adminId ) {
		 String hql = "from Trade bean where id=? and bean.admin.id=?";
		 return ( Trade ) findUnique( hql, userid, adminId );
	}

	public Pagination getPage( Boolean status, Integer selfId, String searchProperty, String searchValue, String orderProperty, String orderDirection, int pageNo, int pageSize, String filterStatus ) {
		Finder f = Finder.create( "select bean from Trade bean where bean.status=:status" );
		f.setParam( "status", status );

		if( selfId != null ){
			f.append( " and bean.admin.id =:selfId " );
			f.setParam( "selfId", selfId );
		}

		createFilter( f, filterStatus );
		createSearch( f, searchProperty, searchValue );
		createOrder( f, orderProperty, orderDirection, "id" );
		
		return find(f, pageNo, pageSize);
	}
	
	/**
	 * 根据
	 * @param status
	 * @param pageNo
	 * @param pageSize
	 * @return
	 * 当前用户必须属于当前管理员， 
	 */
	public Pagination getPage( Boolean status,  Integer groupId, List< Integer > idList,  int pageNo, int pageSize ){
		
		StringBuilder sqls = new StringBuilder( );
		sqls.append( "(" );
		for( int i = 0; i < idList.size( ); i++ ){
			
			sqls.append( " admin_id=" );
			sqls.append( idList.get( i ) );
			
			if( i < idList.size( ) - 1 ){
				sqls.append( " or " );
			}
			
		}
		sqls.append( ")" );
	
		
		String sql = sqls +  " and find_in_set(" + groupId + ",oriented_group)";
		
		if( status != null ){
			sql = " status=" + ( status ? 1 : 0 ) + " and " + sql;
		}
		
		Criteria c = this.createCriteria( sql ); // 创建对象
		createOrder( c, "id", "desc", "id" );
		Pagination p = this.findByCriteria( c, pageNo, pageSize );
		return p;
	}

	public Trade save( Trade bean ) {
		getSession( ).save( bean );
		return bean;
	}

	@Override
	protected Class< Trade > getEntityClass( ) {
		return Trade.class;
	}

}
